import todo from '../../component/v2/plugins/todo'
import selectable from '../../component/v2/plugins/selectable'
import solarLunar from '../../component/v2/plugins/solarLunar/index'
import timeRange from '../../component/v2/plugins/time-range'
import week from '../../component/v2/plugins/week'
import holidays from '../../component/v2/plugins/holidays/index'
import plugin from '../../component/v2/plugins/index'
import {
  Toast,
  Loading
} from "../../utils/util";
import dayjs from '../../utils/dayjs'
plugin
  .use(todo)
  .use(solarLunar)
  .use(selectable)
  .use(week)
  // .use(timeRange)
  .use(holidays)

const conf = {
  data: {
    calendarConfig: {
      theme: 'elegant',
      showHolidays: true,
      emphasisWeek: true,
      chooseAreaMode: true,
      autoChoosedWhenJump: true
    },
    modalName: '',
    selectDate: '',
    todoContent: '',
    todoName: "",
    TouchName: "",
    todoList: [],
    weather: {},
    form: {
      travelFrom: "",
      travelType: '0',
      travelTo: "",
      travelTime: dayjs(new Date()).format('YYYY-MM-DD'),
      time: "08:00",
    },
    travelList: [],
    pickerList: [],
    actionBtn: [{
        text: '跳转指定日期',
        action: 'jump',
        color: 'olive'
      },
      {
        text: '获取当前已选',
        action: 'getSelectedDates',
        color: 'red'
      },
      {
        text: '取消选中日期',
        action: 'cancelSelectedDates',
        color: 'mauve'
      },
      {
        text: '设置待办事项',
        action: 'setTodos',
        color: 'cyan'
      },
      {
        text: '删除指定代办',
        action: 'deleteTodos',
        color: 'pink'
      },
      {
        text: '清空待办事项',
        action: 'clearTodos',
        color: 'red'
      },
      {
        text: '获取所有代办',
        action: 'getTodos',
        color: 'purple'
      },
      {
        text: '禁选指定日期',
        action: 'disableDates',
        color: 'olive'
      },
      {
        text: '指定可选区域',
        action: 'enableArea',
        color: 'pink'
      },
      {
        text: '指定特定可选',
        action: 'enableDates',
        color: 'red'
      },
      {
        text: '选中指定日期',
        action: 'setSelectedDates',
        color: 'cyan'
      },
      {
        text: '周月视图切换',
        action: 'switchView',
        color: 'orange'
      },
      {
        text: '获取自定义配置',
        action: 'getConfig',
        color: 'olive'
      },
      {
        text: '获取日历面板日期',
        action: 'getCalendarDates',
        color: 'purple'
      }
    ]
  },
  onLoad(){
    this.setData({
      pickerList: wx.getStorageSync('dictList').filter(item => item.dictValue == 'tranleType')[0]['dictJson'].map(item => item.key) ?? [],
      weather: wx.getStorageSync('cityMap')['weather'].filter(item => item.date == dayjs(new Date()).format('YYYY-MM-DD'))[0]
    })
    
  },
  async afterTapDate(e) {
    console.log('afterTapDate', e.detail)
    let selectDate = e.detail;
    let todoTime = `${selectDate['year']}-${selectDate['month']<10 ? '0'+selectDate['month'] : selectDate['month']}-${selectDate['date']<10 ? '0'+selectDate['date'] : selectDate['date']}`;
    this.setData({
      selectDate: todoTime
    })
    this.getTodoList()
    this.getTravelList()

    let weatherDay = wx.getStorageSync('cityMap')['weather'].filter(item => item.date == todoTime)
    if(weatherDay.length == 0){
      Toast("none", "目前只能查看未来七天天气情况");
      return;
    }
    this.setData({
      weather: wx.getStorageSync('cityMap')['weather'].filter(item => item.date == todoTime)[0]
    })
  },
  whenChangeMonth(e) {
    console.log('whenChangeMonth', e.detail)
  },
  whenChangeWeek(e) {
    console.log('whenChangeWeek', e.detail)
  },
  takeoverTap(e) {
    console.log('takeoverTap', e.detail)
  },
  afterCalendarRender(e) {
    console.log('afterCalendarRender', e)
    // 获取日历组件上的 calendar 对象
    // const calendar = this.selectComponent('#calendar').calendar
    // console.log('afterCalendarRender -> calendar', calendar)
  },
  onSwipe(e) {
    console.log('onSwipe', e)
  },
  showToast(msg) {
    if (!msg || typeof msg !== 'string') return
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 1500
    })
  },
  generateRandomDate(type) {
    let random = ~~(Math.random() * 10)
    switch (type) {
      case 'year':
        random = 201 * 10 + ~~(Math.random() * 10)
        break
      case 'month':
        random = (~~(Math.random() * 10) % 9) + 1
        break
      case 'date':
        random = (~~(Math.random() * 100) % 27) + 1
        break
      default:
        break
    }
    return random
  },
  async getTodoList() {
    const res = await wx.cloud.database().collection('todoList').where({
      userId: wx.getStorageSync('uid'),
      todoTime: this.data.selectDate,
      tableType: "todo"
    }).get()
    this.setData({
      todoList: [...res.data]
    })
    this.getTodoTags()
  },
  async getTravelList() {
    const res = await wx.cloud.database().collection('travel').where({
      travelUserId: wx.getStorageSync('uid'),
      travelTime: this.data.selectDate,
    }).get()
    this.setData({
      travelList: [...res.data].map(item => ({
        ...item,
        date: `${item.travelTime.split("-")[1]}-${item.travelTime.split("-")[2]}`,
        travelTypes: this.data.pickerList.filter((it, index) => index == item.travelType)[0]
      }))
    })
    this.getTodoTags()
  },
  async getTodoTags() {
    const travelData = await wx.cloud.database().collection('travel').where({
      travelUserId: wx.getStorageSync('uid'),
    }).get()
    const todoData = await wx.cloud.database().collection('todoList').where({
      userId: wx.getStorageSync('uid'),
      tableType: "todo"
    }).get()
    console.log(travelData, todoData)
    var newArray = travelData.data.map(item => ({
      ...item,
      newTime: item.travelTime
    })).concat(todoData.data.map(item => ({
      ...item,
      newTime: item.todoTime
    })))
    const calendar = this.selectComponent('#calendar').calendar
    calendar['clearTodos']() //先清除
    // 使用 reduce 方法对数组进行分组
    const groupedData = newArray.reduce((acc, obj) => {
      const key = obj["newTime"];
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(obj);
      return acc;
    }, {});
    console.log(groupedData)
    Object.keys(groupedData).forEach(item => {
      const dates = [{
        year: dayjs(item).format('YYYY'),
        month: dayjs(item).format('MM'),
        date: dayjs(item).format('DD'),
        todoText: true? '':groupedData[item].length
      }]
      calendar['setTodos']({
        showLabelAlways: true,
        dates
      })
    })

  },
  delAllTodo(e) {
    let that = this;
    let id = e.target.dataset.id;
    wx.cloud.database().collection('todoList').where({
      userId: wx.getStorageSync('uid'),
      todoTime: that.selectDate,
      tableType: "todo"
    }).remove({
      success: function (res) {
        Toast("none", "删除成功");
        that.getTodoList()
      }
    })
  },
  delTodo(e) {
    let that = this;
    let id = e.target.dataset.id;
    wx.cloud.database().collection('todoList').doc(id).remove({
      success: function (res) {
        Toast("none", "删除成功");
        that.getTodoList()
      }
    })
  },
  delTravel(e) {
    let that = this;
    let id = e.target.dataset.id;
    wx.cloud.database().collection('travel').doc(id).remove({
      success: function (res) {
        Toast("none", "删除成功");
        that.getTravelList()
      }
    })
  },
  setModal(e) {
    const calendar = this.selectComponent('#calendar').calendar
    let selectDate = calendar['getSelectedDates']()[0]
    let todoTime = `${selectDate['year']}-${selectDate['month']<10 ? '0'+selectDate['month'] : selectDate['month']}-${selectDate['date']<10 ? '0'+selectDate['date'] : selectDate['date']}`;
    this.setData({
      modalName: e.target.dataset.event,
      selectDate: todoTime,
    })
  },
  formSubmit(e) {
    let that = this;
    let formDate = e.detail.value;
    for (var i in formDate) {
      if (formDate[i] == '') {
        const msg = i == 'todoName' ? '待办事项' : '详细内容';
        Toast("error", msg + "不能为空");
        return;
      }
    }
    console.log(formDate)
    wx.cloud.database().collection('todoList').add({
      data: {
        todoName: formDate['todoName'],
        todoContent: formDate['todoContent'],
        todoTime: formDate['todoTime'],
        userId: wx.getStorageSync('uid'),
        tableType: "todo"
      },
      success(res) {
        console.log(res)
        Toast("none", "设置成功");
        that.setData({
          modalName: '',
          todoName: '',
          todoContent: ''
        })
        that.getTodoList()
      },
      fail(res) {
        Toast("none", "设置失败");
      },
    })
  },
  formSubmitAp(e) {
    let that = this;
    let formDate = e.detail.value;
    if(formDate['travelFrom'] == ""){
      Toast("none", "出发地不能为空");
      return;
    }
    if(formDate['travelTo'] == ""){
      Toast("none", "目的地不能为空");
      return;
    }
    if(that.data.form.travelType != '2' && formDate['travelNo'] == ""){
      Toast("none", "航班号/动车号不能为空");
      return;
    }
    if(formDate['time'] == ""){
      Toast("none", "详细时间不能为空");
      return;
    }
    wx.cloud.database().collection('travel').add({
      data: {
        travelFrom: formDate['travelFrom'],
        travelTo: formDate['travelTo'],
        travelTime: that.data.selectDate,
        travelUserId: wx.getStorageSync('uid'),
        travelNo: formDate['travelNo'],
        travelType: that.data.form.travelType,
        time: formDate['time']
      },
      success(res) {
        Toast("none", "设置成功");
        that.setData({
          modalName: '',
          'form.travelType': '0','form.travelFrom': '','form.travelTo': '','form.travelNo': '','form.time': '08:00',
        })
        that.getTravelList()
      },
      fail(res) {
        Toast("none", "设置失败");
      },
    })
  },
  PickerChange(e){
    this.setData({
      'form.travelType': e.detail.value
    })
  },
  hideModal() {
    this.setData({
      modalName: '',
      todoName: '',
      todoContent: ''
    })
  },
  // ListTouch触摸开始
  ListTouchStart(e) {
    console.log(e)
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
  },
  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection == 'left') {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },
  handleAction(e) {
    const {
      action,
      disable
    } = e.currentTarget.dataset
    if (disable) {
      this.showToast('抱歉，还不支持～😂')
    }
    this.setData({
      rst: []
    })
    const calendar = this.selectComponent('#calendar').calendar
    const {
      year,
      month
    } = calendar.getCurrentYM()
    switch (action) {
      case 'config':
        calendar
          .setCalendarConfig({
            showLunar: false,
            theme: 'elegant',
            multi: true
          })
          .then(conf => {
            console.log('设置成功：', conf)
          })
        break
      case 'getConfig':
        const config = calendar.getCalendarConfig()
        this.showToast('请在控制台查看结果')
        console.log('自定义配置: ', config)
        break
      case 'jump': {
        const year = this.generateRandomDate('year')
        const month = this.generateRandomDate('month')
        const date = this.generateRandomDate('date')
        const config = calendar.getCalendarConfig()
        if (config.weekMode) {
          calendar['weekModeJump']({
            year,
            month,
            date
          })
        } else {
          calendar[action]({
            year,
            month,
            date
          })
        }
        break
      }
      case 'getSelectedDates': {
        const selected = calendar[action]()
        if (!selected || !selected.length)
          return this.showToast('当前未选择任何日期')
        this.showToast('请在控制台查看结果')
        console.log('get selected dates: ', selected)
        const rst = selected.map(item => JSON.stringify(item))
        this.setData({
          rst
        })
        break
      }
      case 'cancelSelectedDates':
        const selected = calendar.getSelectedDates()
        calendar[action](selected)
        break
      case 'setTodos': {
        const dates = [{
          year,
          month,
          date: this.generateRandomDate('date'),
          todoText: Math.random() * 10 > 5 ? '回家' : ''
        }]
        calendar[action]({
          showLabelAlways: true,
          dates
        })
        console.log('set todo: ', dates)
        break
      }
      case 'deleteTodos': {
        const todos = [...calendar.getTodos()]
        if (todos.length) {
          calendar[action]([todos[0]]).then(() => {
            const _todos = [...calendar.getTodos()]
            setTimeout(() => {
              const rst = _todos.map(item => JSON.stringify(item))
              this.setData({
                  rst
                },
                () => {
                  console.log('delete todo: ', todos[0])
                }
              )
            })
          })
        } else {
          this.showToast('没有待办事项')
        }
        break
      }
      case 'clearTodos':
        const todos = [...calendar.getTodos()]
        if (!todos || !todos.length) {
          return this.showToast('没有待办事项')
        }
        calendar[action]()
        
        break
      case 'getTodos': {
        const selected = calendar[action]()
        if (!selected || !selected.length)
          return this.showToast('未设置待办事项')
        const rst = selected.map(item => JSON.stringify(item))
        rst.map(item => JSON.stringify(item))
        this.setData({
          rst
        })
        break
      }
      case 'disableDates':
        calendar[action]([{
          year,
          month,
          date: this.generateRandomDate('date')
        }])
        break
      case 'enableArea': {
        let sDate = this.generateRandomDate('date')
        let eDate = this.generateRandomDate('date')
        if (sDate > eDate) {
          ;
          [eDate, sDate] = [sDate, eDate]
        }
        const area = [`${year}-${month}-${sDate}`, `${year}-${month}-${eDate}`]
        calendar[action](area)
        this.setData({
          rstStr: JSON.stringify(area)
        })
        break
      }
      case 'enableDates':
        const dates = [
          `${year}-${month}-${this.generateRandomDate('date')}`,
          `${year}-${month}-${this.generateRandomDate('date')}`,
          `${year}-${month}-${this.generateRandomDate('date')}`,
          `${year}-${month}-${this.generateRandomDate('date')}`,
          `${year}-${month}-${this.generateRandomDate('date')}`
        ]
        calendar[action](dates)
        this.setData({
          rstStr: JSON.stringify(dates)
        })
        break
      case 'switchView':
        if (!this.week) {
          calendar[action]('week').then(calendarData => {
            console.log('switch success!', calendarData)
          })
          this.week = true
        } else {
          calendar[action]().then(calendarData => {
            console.log('switch success!', calendarData)
          })
          this.week = false
        }
        break
      case 'setSelectedDates':
        const toSet = [{
            year,
            month,
            date: this.generateRandomDate('date')
          },
          // {
          //   year,
          //   month,
          //   date: this.generateRandomDate('date')
          // }
        ]
        calendar[action](toSet)
        break
      case 'getCalendarDates':
        this.showToast('请在控制台查看结果')
        console.log(
          calendar.getCalendarDates({
            lunar: true
          })
        )
        break
      default:
        break
    }
  },
  onShow() {
    this.setData({
      selectDate: dayjs(new Date()).format("YYYY-MM-DD")
    })
    this.getTodoList()
    this.getTravelList()
  }
}

Page(conf)